package com.allqj.sfx.infrastructure.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;

/**
 * @author sjw
 * @className utils
 * @date 2022/7/19 10:12
 * @description: TODO
 */

/**
 * json操作
 */
public class JsonUtil {
    private static final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    public static <T> String objectToJson(T obj) {
        try {
            return gson.toJson(obj);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return obj.toString();
    }

    public static <T> T jsonToObject(String json, Class<T> classType, String pattern) {
        Gson gson = new GsonBuilder().setDateFormat(pattern).create();
        try {
            return gson.fromJson(json, classType);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static <T> T jsonToObject(String json, Class<T> classType) {
        try {
            return gson.fromJson(json, classType);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static <T> T jsonToObject(String json, Type classType) {
        try {
            return gson.fromJson(json, classType);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

}

